import config from '@/config';
import { createRoot, Root } from 'react-dom/client';
import { name } from '@/package.json';

const id = 'cls-tools-confirm';
let root: Root | null = null;
function confirmRender() {
  let wrapperEle = document.querySelector(`#${id}`);
  if (!wrapperEle) {
    wrapperEle = document.createElement('div');
    wrapperEle.id = id;
    document.body.appendChild(wrapperEle);
  }
  return wrapperEle;
}

export function confirmMessage({
  title = '标题',
  description = '描述',
  confirmText = '确定',
  cancelText = '取消',
  container,
}: {
  title?: string;
  description?: React.ReactNode;
  confirmText?: string;
  cancelText?: string;
  container?: string;
}) {
  return new Promise((resolve, reject) => {
    const confirmEle = confirmRender();
    let containerEle = null;
    if (container) {
      containerEle =
        document.querySelector(name)?.shadowRoot?.querySelector(container) ||
        document.querySelector(container);
    }

    // console.log(containerEle);

    const alertDialog = (
      <AlertDialog defaultOpen={true}>
        <AlertDialogContent
          container={containerEle}
          style={{
            zIndex: config.alertDialogZIndex,
          }}
        >
          <AlertDialogHeader>
            <AlertDialogTitle>{title}</AlertDialogTitle>
            <AlertDialogDescription
              className="overflow-auto"
              style={{
                maxHeight: '50vh',
              }}
            >
              {description}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction
              onClick={() => {
                resolve(true);
              }}
            >
              {confirmText}
            </AlertDialogAction>
            <AlertDialogCancel
              onCanPlay={() => {
                resolve(false);
              }}
            >
              {cancelText}
            </AlertDialogCancel>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    );
    if (root) {
      root.unmount();
    }
    root = createRoot(confirmEle);
    root.render(alertDialog);
  });
}
